package com.example.qt.ptplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.qt.ptplatform.entity.UserFollow;
import com.example.qt.ptplatform.mapper.UserFollowMapper;
import com.example.qt.ptplatform.service.UserFollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
public class UserFollowServiceImpl implements UserFollowService {

    @Autowired
    private UserFollowMapper userFollowMapper;

    @Override
    @Transactional
    public boolean followUser(Integer followerId, Integer followedId) {
        if (followerId == null || followedId == null || followerId.equals(followedId)) {
            return false;
        }

        // 检查是否已关注
        if (isFollowing(followerId, followedId)) {
            return false;
        }

        UserFollow follow = new UserFollow();
        follow.setFollowerId(followerId);
        follow.setFollowedId(followedId);
        follow.setCreateTime(LocalDateTime.now());

        return userFollowMapper.insert(follow) > 0;
    }

    @Override
    @Transactional
    public boolean unfollowUser(Integer followerId, Integer followedId) {
        LambdaQueryWrapper<UserFollow> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserFollow::getFollowerId, followerId)
                .eq(UserFollow::getFollowedId, followedId);

        return userFollowMapper.delete(wrapper) > 0;
    }

    @Override
    public boolean isFollowing(Integer followerId, Integer followedId) {
        if (followerId == null || followedId == null) {
            return false;
        }
        return userFollowMapper.existsByFollowerAndFollowed(followerId, followedId) > 0;
    }

    @Override
    public List<Integer> getFollowingList(Integer userId) {
        if (userId == null) {
            return Collections.emptyList();
        }
        return userFollowMapper.selectFollowingIds(userId);
    }

    @Override
    public List<Integer> getFollowerList(Integer userId) {
        if (userId == null) {
            return Collections.emptyList();
        }
        return userFollowMapper.selectFollowerIds(userId);
    }

    @Override
    public int getFollowingCount(Integer userId) {
        return userFollowMapper.countByFollowerId(userId);
    }

    @Override
    public int getFollowerCount(Integer userId) {
        return userFollowMapper.countByFollowedId(userId);
    }
}